﻿#include "followupdater.h"

#pragma execution_character_set("utf-8")

bool FollowUpdater::handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa)
{
    osgViewer::View *view=static_cast<osgViewer::View*>(&aa);
    if ( !view || !_target || ea.getEventType()!=osgGA::GUIEventAdapter::FRAME ) return false;
    osgGA::OrbitManipulator* orbit=dynamic_cast<osgGA::OrbitManipulator*>( view->getCameraManipulator() );
    if(orbit){
        osg::Matrix matrix=computeTargetToWorldMatrix( _target.get() );
        //这里进行了一个矩阵变换，局部节点*变换矩阵=世界（坐标系）节点
        osg::Vec3d targetCenter=this->_target->getBound().center()*matrix;
        orbit->setCenter( targetCenter );
    }
    return false;
}

osg::Matrix FollowUpdater::computeTargetToWorldMatrix(osg::Node *node) const
{
    osg::Matrix l2w;
    if ( node && node->getNumParents()>0 )
    {
        osg::Group* parent = node->getParent(0);
        l2w = osg::computeLocalToWorld( parent->getParentalNodePaths()[0] );
//        l2w=osg::computeLocalToWorld(node->getParentalNodePaths()[0]);
    }
    return l2w;
}
